import requests
import json
import base64
from urllib.parse import quote
import os
from playsound import playsound

class BaiduTTS:
    def __init__(self):
        # API配置信息
        self.API_KEY = '44kNzmCeZNnLHoUcNiGYnyI7'
        self.SECRET_KEY = '7sNV1osooTqJliQB1aHB5lJKEKlLrg5f'
        self.access_token = None
        
    def get_access_token(self):
        """获取access_token"""
        url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={self.API_KEY}&client_secret={self.SECRET_KEY}"
        
        response = requests.post(url)
        if response.status_code == 200:
            result = response.json()
            self.access_token = result['access_token']
            return self.access_token
        else:
            print(f"获取access_token失败: {response.status_code}")
            return None

    def text_to_speech(self, text, params=None):
        """文字转语音"""
        if not self.access_token:
            self.access_token = self.get_access_token()
            
        if not self.access_token:
            print("无法获取access_token")
            return False

        # 默认参数
        default_params = {
            'spd': 9,  # 语速，取值0-15
            'pit': 5,  # 音调，取值0-15
            'vol': 5,  # 音量，取值0-15
            'per': 0,  # 发音人，0为女声，1为男声，3为度逍遥，4为度丫丫
        }

        # 更新参数
        if params:
            default_params.update(params)

        url = "https://tsn.baidu.com/text2audio"
        
        params = {
            'tex': quote(text),
            'tok': self.access_token,
            'cuid': 'python_tts',
            'ctp': 1,
            'lan': 'zh',
            'aue': 3,  # mp3格式
            **default_params
        }
        
        try:
            response = requests.get(url, params=params)
            
            # 检查是否返回音频数据
            if response.headers['Content-Type'].startswith('audio/'):
                # 保存音频文件
                audio_file = "output.mp3"
                with open(audio_file, 'wb') as f:
                    f.write(response.content)
                print(f"已保存音频文件: {audio_file}")
                
                # 播放音频
                playsound(audio_file)
                return True
            else:
                error_msg = response.json()
                print(f"转换失败: {error_msg}")
                return False
                
        except Exception as e:
            print(f"请求失败: {str(e)}")
            return False

def main():
    # 使用示例
    tts = BaiduTTS()
    
    # 要转换的文本
    text = input("请输入要转换的文字: ")
    
    # 可选：自定义参数
    params = {
        'spd': 9,  # 语速
        'pit': 5,  # 音调
        'vol': 5,  # 音量
        'per': 0   # 发音人
    }
    
    # 执行转换
    tts.text_to_speech(text, params)

if __name__ == "__main__":
    main()
